﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using mamnontuoitho7.AppCode;
using System.Data;
using System.IO;

namespace mamnontuoitho7.backend
{
    public partial class KidEdit : System.Web.UI.Page
    {
        private Class _class = new Class();
        protected Kid _kid = new Kid();
        protected General _general = new General();
        protected ThumbnailClass _thumbnailClass = new ThumbnailClass();
        protected DataRow _dtrKid;

        protected String _kidID = "";
        protected String _namePage = "";
        protected String _classID = "";
        protected String _className = "";
        protected String _kidAvatar = "";
        protected String _kidFullName = "";

        protected void Page_Load(object sender, EventArgs e)
        {

            //Check Role Admin
            if (Session["memberID"].ToString() != "" && (ConstantClass.permissionInfo).IndexOf(Session["role"].ToString() + ",") != -1)
            {
                try
                {

                    if (Request.QueryString["hidKidID"] != null && Request.QueryString["hidNamePage"] != null)
                    {
                        _kidID = Request.QueryString["hidKidID"].ToString();
                        _namePage = Request.QueryString["hidNamePage"].ToString();


                        if (Request.QueryString["hidClassID"] != null && Request.QueryString["hidClassName"] != null)
                        {
                            hidClassID.Value = Request.QueryString["hidClassID"].ToString();
                            hidClassName.Value = Request.QueryString["hidClassName"].ToString();
                        }

                        if (Request.QueryString["hidParentID"] != null)
                        {
                            hidParentID.Value = Request.QueryString["hidParentID"].ToString();
                        }
                        if (!IsPostBack)
                        {
                            loadClassList();
                            LoadKidInformation(_kidID);

                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Response.Redirect(ConstantClass._errorAdminPage);
                }
            }
            else
            {
                Response.Redirect(ConstantClass._errorLoginPage);
            }
        }


        /// <summary>
        /// Load Class List and put in Dropdownlist
        /// </summary>
        private void loadClassList()
        {
            DataTable dttClass = _class.GetClassList("0");
            ddlClass.DataSource = dttClass;
            ddlClass.DataTextField = "ClassName";
            ddlClass.DataValueField = "ClassID";
            ddlClass.DataBind();
        }

        /// <summary>
        /// Load kid information from database
        /// </summary>
        private void LoadKidInformation(String kidID)
        {
            //Get Kid information
            _dtrKid = _kid.GetKidInformation(kidID);

            ddlClass.SelectedValue = _dtrKid["ClassID"].ToString();
            txtClassPosition.Text = _dtrKid["ClassPosition"].ToString();
            txtKidFirstName.Text = _dtrKid["KidFirstName"].ToString();
            txtKidLastName.Text = _dtrKid["KidLastName"].ToString();

            txtKidBirthday.Text = _dtrKid["KidBirthday"].ToString();
            hidImageKid.Value = _kidAvatar = _dtrKid["KidAvatar"].ToString();
            imgKid.ImageUrl = "../images/avatar/kid/" + (_kidAvatar == "" ? ConstantClass._kidDefaultAvatar : _kidAvatar);

            txtFatherName.Text = _dtrKid["Father"].ToString();
            txtMotherName.Text = _dtrKid["Mother"].ToString();

            txtKidGuadianFullName.Text = _dtrKid["FullName"].ToString();
            ddlKidSex.SelectedValue = _dtrKid["KidSex"].ToString() == "0" ? "0" : "1";
            ddlKidVisible.SelectedValue = _dtrKid["KidVisible"].ToString().ToLower();

            _kidFullName = _dtrKid["KidLastName"].ToString() + " " + _dtrKid["KidFirstName"].ToString();
        }

        /// <summary>
        /// Update kid information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnKidEdit_Click(object sender, EventArgs e)
        {
            try
            {

                if (Request.QueryString["hidKidID"] != null)
                {
                    _kidID = Request.QueryString["hidKidID"].ToString();
                    _kidAvatar = hidImageKid.Value;

                    string avatar = txtKidLastName.Text.Trim() + "-" + txtKidFirstName.Text.Trim() + "-" + _kidID;
                    if (fulKidAvatar.FileName != "" || fulKidAvatar.FileName == null)
                    {

                        if (fulKidAvatar.FileBytes.Count() / 1024 > 6144)
                        {
                            lblNoticeKidEdit.Visible = true;
                            lblNoticeKidEdit.Text = "Dung lượng hình ảnh phải dưới 6MB.";
                            return;
                        }

                        avatar = _thumbnailClass.UploadImage2(fulKidAvatar, Request.PhysicalApplicationPath + "images/avatar/kid/", avatar, 128, 128, _kidAvatar);

                        if (avatar == "")
                        {
                            lblNoticeKidEdit.Visible = true;
                            lblNoticeKidEdit.Text = "Hình của bé mới không thể upload được. File hình chỉ hỗ trợ những file: jpg, jpeg, gif, png, bmp, tiff";
                            return;
                        }
                    }
                    else
                    {
                        avatar = _kidAvatar;
                    }

                    bool checkUpdate = _kid.UpdateKid(_kidID,
                                                       txtKidFirstName.Text.Trim(),
                                                       txtKidLastName.Text.Trim(),
                                                       ddlKidSex.SelectedValue.ToString(),
                                                       txtKidBirthday.Text.Trim(),
                                                       txtMotherName.Text.Trim(),
                                                       txtFatherName.Text.Trim(),
                                                       avatar,
                                                       ddlKidVisible.SelectedValue,
                                                       ddlClass.SelectedValue);


                    if (checkUpdate)
                    {
                        lblNoticeKidEdit.Visible = true;
                        lblNoticeKidEdit.Text = "Thông tin của bé đã được cập nhật.";

                        hidImageKid.Value = avatar;
                        imgKid.ImageUrl = "../images/avatar/kid/" + (avatar == "" ? ConstantClass._kidDefaultAvatar : avatar);

                        _kidFullName = txtKidLastName.Text.Trim() + " " + txtKidFirstName.Text.Trim();
                    }
                    else
                    {
                        lblNoticeKidEdit.Visible = true;
                        lblNoticeKidEdit.Text = "Có lỗi hệ thống không thể cập nhật được.";
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Response.Redirect(ConstantClass._errorAdminPage);

            }

        }

        /// <summary>
        /// Callback information of the child
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnCancle_Click(object sender, EventArgs e)
        {
            try
            {
                if (Request.QueryString["hidKidID"] != null)
                {
                    _kidID = Request.QueryString["hidKidID"].ToString();
                    LoadKidInformation(_kidID);
                    lblNoticeKidEdit.Visible = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Response.Redirect(ConstantClass._errorAdminPage);
            }
        }


        //Delete Kid
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            if (Request.QueryString["hidKidID"] != null)
            {
                try
                {
                    _kidID = Request.QueryString["hidKidID"].ToString();
                    _kid.DeleteKid(_kidID);

                }
                catch (Exception ex)
                {
                    lblNoticeKidEdit.Visible = true;
                    lblNoticeKidEdit.Text = "Phải xóa thông tin trên tường và tình trạng sức khỏe của bé trước khi xóa bé.";
                    Console.WriteLine(ex.Message);
                    return;
                }

                try
                {

                    //Delete old image
                    if (hidImageKid.Value != "")
                    {
                        string LocalFile = Request.PhysicalApplicationPath + "images/avatar/kid/" + hidImageKid.Value;
                        if (File.Exists(LocalFile))
                            File.Delete(LocalFile);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                Response.Redirect("../backend/KidList.aspx");
            }
        }

        ///// <summary>
        ///// Updload kid avatar image
        ///// </summary>
        ///// <returns></returns>
        //private string UploadImage()
        //{
        //    try
        //    {
        //        if (!string.IsNullOrEmpty(fulKidAvatar.FileName))
        //        {
        //            string[] splitFileName = (fulKidAvatar.FileName.Split(new char[] { '.' }));
        //            string fileExtension = splitFileName[splitFileName.Length - 1].Trim().ToLower();
        //            if (fileExtension == "jpg" || fileExtension == "gif" || fileExtension == "jpeg" || fileExtension == "png" || fileExtension == "bmp" || fileExtension == "tiff")
        //            {
        //                string FilePath = Request.PhysicalApplicationPath + "images/avatar/kid/";
        //                string code = txtKidLastName.Text.Trim() + "-" + txtKidFirstName.Text.Trim() + "-" + _kidID;
        //                string name = txtKidLastName.Text.Trim() + "-" + txtKidFirstName.Text.Trim() + "-" + _kidID;
        //                ThumbnailClass thumb = new ThumbnailClass();
        //                String filename = thumb.UploadImage(fulKidAvatar, FilePath, code, name, 150, true, false);

        //                _kidAvartar = filename;

        //                return filename;
        //            }
        //            else
        //            {
        //                String script = "<script language=JavaScript>alert('Chỉ hỗ trợ những file: jpg, jpeg, gif, png, bmp, tiff')</script>";
        //                Page.ClientScript.RegisterStartupScript(typeof(Page), "alert", script);
        //            }
        //        }

        //        return null;
        //    }
        //    catch (Exception ex)
        //    {
        //        Console.WriteLine(ex.Message);
        //        return null;
        //    }
        //}


    }
}